#!/usr/bin/env python3
# processes https://malscraper.azurewebsites.net/
# until I setup a db for bookkeeping of my own this is my ghetto solution
import sys
import xmltodict
from models import Data, Summary, Anime

# global state because I couldn't design this utility to be better
category = 'NONE'
in_list = 0
body1 = '''<html>
<head>
<title>strlst anime index</title>
<meta charset="utf-8"/>
<link rel='stylesheet' type='text/css' href='../style-list.css'>
</head>

<body>
<h1><a href="../index.html">strlst</a> anime index</h1>

<p>listing consumed anime, done this way because all other list keeping utilities suck</p>
<p>note:
<ul>
    <li>no ratings, ratings are only a temporal concept anyway</li>
    <li>notable anime denoted with a little (++) (in accordance with newspeak)</li>
    <li>autogenerated using <a href='https://notabug.org/strlst/malscraperparser'>https://notabug.org/strlst/malscraperparser</a></li>
</ul>
</p>
'''
body2 = '''
</body>
</html>
'''

# designed to generate actual html for my own list
# terrible solution
def gen_list(_, entry):
    global in_list
    global category
    s = Summary()
    a = Anime()
    if a.match_structure(entry):
        if a.data['my_status'] != category:
            if in_list:
                in_list = 0
                print('</ul>')
            category = a.data['my_status']
            print('<h2>{c}</h2>'.format(c=category))

        if not in_list:
            in_list = 1
            print('<ul>')

        print('    <li>{title}{fav} <b>({watched}/{total_eps} eps.) ({fr} - {to})</b></li>'.format(
title     = a.data['series_title'],
fav       = ' (++)' if a.data['my_score'] != '0' else '',
watched   = a.data['my_watched_episodes'],
total_eps = a.data['series_episodes'],
fr        = a.data['my_start_date'],
to        = a.data['my_finish_date'],
))

        if len(a.data['my_comments']) > 0:
            in_list = 0        
            print('</ul>')
            print('	<p>{c}</p>'.format(c=a.data['my_comments'].replace('\n', '</p><p>')))

    return True

# unused
def handle_entry(_, entry):
    s = Summary()
    a = Anime()
    if a.match_structure(entry):
        print(a)
    elif s.match_structure(entry):
        print(s)

    return True

if __name__ == '__main__':
    xml = sys.stdin.read()
    print(body1)
    xmltodict.parse(xml, item_depth=2, item_callback=gen_list)
    print(body2)
